import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, history } from 'umi'
import { findItemByTree } from '@/utils/functions'
import { message, Button, Modal, Form, Input, Row, Col, TreeSelect, Divider, Popconfirm } from 'antd'
import {deleteOrgGroup, updateOrgGroup, getOrgGroupPageList, addUserGroup, getOrgGroupById} from '../service'

const TableList = (props) => {
  const { global = {} } = props;
  const {options = {}} = global;
  const {orgTree} = options;
  const [finalTree,setFinalTree] = useState([]);
  const actionRef = useRef();
  const [form] = Form.useForm();
  const [title, setTitle] = useState('');
  const [visible, setVisible] = useState(null);
  const [groupInfo, setGroupInfo] = useState({});
  const [operateType, setOperateType] = useState(null);

  useEffect(() => {
    setFinalTree(orgTree);
  }, [orgTree]);

  const traverseAndSetTree = (tree,checkedList) => {
    tree.forEach(item => {
      checkedList.forEach(valueItem => {
        if (valueItem === item.value){
          item.children = [];
        }
      });
      if (item.children.length>0)
        traverseAndSetTree(item.children,checkedList);
    })
  };

  const setTree = (values) => {
    let localOrgTree =JSON.parse(JSON.stringify(orgTree));
    traverseAndSetTree(localOrgTree,values);
    setFinalTree(localOrgTree);
  };

  const onChange = (value, node, extra) => {
    let theSameChildren = [];
    let checkedNode = findItemByTree(orgTree,extra.triggerValue);
    let findChildren = (tree, ids) => {
      tree.forEach(item => {
        ids.forEach(id => {
          if (item.value === id)
            theSameChildren.push(id);
        });
        if (item.children.length>0)
          findChildren(item.children,ids)
      })
    };
    findChildren(checkedNode.children,value);
    let finalValues = [];
    value.forEach(item => {
      if (theSameChildren.indexOf(item) < 0)
        finalValues.push(item);
    });
    setTree(finalValues);
    form.setFieldsValue({orgIds:finalValues});
  };

  const addGroup = () => {
    setVisible(true);
    setTitle('添加公司组');
    setOperateType('add');
  };

  const updateGroup = (value) =>{
    setVisible(true);
    setTitle('编辑公司组');
    setOperateType('update');
    setGroupInfo(value);
    let orgIds = [];
    getOrgGroupById(`${value.groupId}`).then(r => {
      for (let i=0; i<r.length; i++){
        orgIds.push(parseInt(r[i].orgId));
      }
      setTree(orgIds);
      form.setFieldsValue({orgIds:orgIds,groupName:value.groupName});
    });
  };

  const delGroup = (values) => {
    deleteOrgGroup(values.groupId).then(r => {
      if (r.flag){
        message.success(`删除公司组成功。`);
      }else {
        message.error(`删除公司组失败。${r.error}`);
      }
      actionRef.current.reload();
    })
  };


  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
  };

  const handleSubmit = (values) => {
    setVisible(false);
    if (operateType === 'add'){
      let data = [];
      values.orgIds.forEach(item => {
        let dataObj = {
          groupName: values.groupName,
          orgId: item
        };
        data.push(dataObj)
      });
      addUserGroup(data).then(r => {
        if (r.flag){
          message.success(`新增公司组成功。`);
        }else {
          message.error(`新增公司组失败。${r.error}`);
        }
        actionRef.current.reload();
      });
    }else if (operateType === 'update') {
      let data = {
        groupId: groupInfo.groupId,
        orgGroupEntitys: []
      };
      if (values.orgIds.length >0){
        values.orgIds.forEach(item => {
          data.orgGroupEntitys.push({
            groupId: groupInfo.groupId,
            groupName: values.groupName,
            orgId: item
          })
        })
      }
      updateOrgGroup(data).then(r => {
        if (r.flag){
          message.success(`编辑公司组成功。`);
        }else {
          message.error(`编辑公司组失败。${r.error}`);
        }
        actionRef.current.reload();
      })
    }
    form.resetFields();
  };

  const columns = [
    {
      title: '序号',
      render:(text,record,index)=>`${index+1}`,
      hideInSearch: true,
      width: '20%'
    },
    {
      title: '公司组名称',
      dataIndex: 'groupName',
      width: '60%'
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '20%',
      render: (item, record) => (
        <>
          {<a onClick={() => updateGroup(record)}>编辑</a>}
          {<Divider type="vertical" />}
          {<Popconfirm title={`是否确认删除?`} onConfirm={() => delGroup(record)} okText="是" cancelText="否">
            <a>删除</a>
          </Popconfirm>}
        </>
      ),
    },
  ];


  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="groupId"
        request={(params) => getOrgGroupPageList(params)}
        toolBarRender={(action, { selectedRows }) => [
          <Button type="primary" onClick={() => addGroup()}>新建</Button>
        ]}
        columns={columns}
      />

      <Modal
        title={title}
        visible={visible}
        footer={null}
        closable={false}
      >
        <Form
          form={form}
          name="normal_login"
          className="login-form"
          onFinish={handleSubmit}
        >
          <Form.Item name="groupName">
            <Input placeholder="公司组名称" />
          </Form.Item>
          <Form.Item name="orgIds">
            <TreeSelect
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={finalTree}
              placeholder="请选择公司"
              multiple={true}
              onChange={onChange}
            />
          </Form.Item>
          <Row justify='end' gutter={16}>
            <Col className="gutter-row" style={{paddingBottom: '20px'}}>
              <Button style={{marginRight: '12px'}} onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">保存</Button>
            </Col>
          </Row>
        </Form>
      </Modal>

    </PageHeaderWrapper>
  )
};

export default connect(({global}) => ({
  global
}))(TableList)
